import { request, USE_MOCK } from './request'

export type RuleStatus = 'enabled' | 'disabled'
export interface Rule {
  id: number
  title: string
  image: string
  link: string
  status: RuleStatus
}

let mockRules: Rule[] = [
  {
    id: 1,
    title: '平台使用须知',
    image: 'https://via.placeholder.com/400x200',
    link: 'https://example.com/rule1',
    status: 'enabled'
  }
]

export async function fetchRules(): Promise<Rule[]> {
  return request({ url: '/rules', method: 'get' }, mockRules)
}

export async function saveRule(rule: Rule) {
  if (USE_MOCK) {
    if (rule.id) {
      const idx = mockRules.findIndex(r => r.id === rule.id)
      if (idx !== -1) mockRules[idx] = { ...rule }
    } else {
      rule.id = mockRules.length ? Math.max(...mockRules.map(r => r.id)) + 1 : 1
      mockRules.push(rule)
    }
    return
  }
  await request({ url: '/rules', method: 'post', data: rule })
}

export async function deleteRule(id: number) {
  if (USE_MOCK) {
    mockRules = mockRules.filter(r => r.id !== id)
    return
  }
  await request({ url: `/rules/${id}`, method: 'delete' })
}
